<template>
  <div class="app-container" v-loading="pageLoading">
    <el-button type="primary" class="fr" @click="createItem" v-permission="'adminRole.add'">创建角色</el-button>
    <div class="filter-container">
      <el-input style="width: 300px;" placeholder="输入查询关键字按回车" clearable prefix-icon="el-icon-search"
        class="filter-item" @keyup.enter.native="research" @clear="research" v-model="query.queryString"></el-input>
    </div>
    <el-row :gutter="20">
      <el-col>
        <z-table :list="list" :tableProps="tableProps" :columns="columns" @editItem="editItem" @deleteItem="deleteItem">
          <template v-slot:operation="v">
            <a href="#" class="text-blue" v-permission="'adminRole.edit'"
              @click.prevent="editItem(v.row, v.$index)">编辑</a>
            <a href="#" class="text-green ml-5" v-permission="'adminRole.edit'"
              @click.prevent="setRoleUser(v.row,v.$index)">关联用户</a>
            <a href="#" class="text-yellow ml-5" v-permission="'adminRole.edit'"
              @click.prevent="setMenuTree(v.row,v.$index)">菜单授权</a>
            <a href="#" class="text-red ml-5" v-permission="'adminRole.delete'"
              @click.prevent="deleteItem(v.row,v.$index)">删除</a>
          </template>
        </z-table>
        <z-pagination :pagination="pagination" :total="total" :page.sync="query.page" :limit.sync="query.size"
          @change="getList"></z-pagination>
      </el-col>
      <el-dialog title="菜单权限分配" class='treeWrap' :visible.sync="menuTreeShow" width="70%">
        <div style="min-height: 36px;">
          <!-- <div style="display:inline-block;width: 120px;font-size: 12px; padding-top: 10px;" v-if="currentId">选择的菜单
          </div> -->
          <el-button type="primary" style="float: left;" v-if="treeData.length" @click="allChoose">
            {{allChooseflag?'全选':'取消全选'}}
          </el-button>
          <el-button type="success" style="float: right;" v-if="currentId && menuCheckChange" :loading="saveMenuLoading"
            @click="saveRoleMenu" v-permission="'adminRole.edit'">保存更改
          </el-button>
        </div>
        <div v-if="currentId" style="padding: 10px 0;" v-loading="treeLoading">
          <el-tree :data="treeData" node-key="id" :default-expand-all="false" :render-after-expand="false"
            :show-checkbox="true" ref="tree" :default-checked-keys="menuIds" :expand-on-click-node="true"
            @check-change="checkChange">
            <div class="custom-tree-node flex" slot-scope="{ data }">
              <span style="font-weight: bold">{{ data.menu_name }}&nbsp;&nbsp;[{{ menuType[data.resource_type] }}]
              </span>
              <el-checkbox-group v-model="data.choose_power_codes">
                <el-checkbox v-for="(i,t) in data.permissionOptions" :key="t" :label="i.value" :value='i.value'
                  @change="changeCheckbox(data,i.value)">
                  {{i.label}}
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </el-tree>
        </div>
      </el-dialog>

    </el-row>
    <z-form-dialog :name="name" :data="data" :formProps="formProps" :fields="fields" @submit="submit"
      :submitLoading="submitLoading" :visible.sync="editFormVisible"></z-form-dialog>
    <!-- 已分配用戶列表 -->
    <el-dialog title="已分配用户" :visible.sync="userRoleDialogShow" width="70%">
      <div class="flex flex-center" style="font-size: 12px; margin-bottom:10px;">
        <el-input style="display:inline-block;width: 160px;" placeholder="输入条件搜索" prefix-icon="el-icon-search"
          size="mini" clearable v-model="userQuery.queryString" @change="researchUser">
        </el-input>
        <div class="flex1"></div>
        <el-button class="ml5" size="mini" type="primary" icon="el-icon-plus" circle plain @click="addUserClick">
        </el-button>
      </div>
      <z-table v-loading="userTableLoading" :list="userList" :tableProps="userTableProps" :columns="userColumns">
        <template v-slot:operation="v">
          <a href="#" class="text-red" @click.prevent="deleteUserRoleItem(v.row, v.$index)"
            v-permission="'adminRole.delete'">删除</a>
        </template>
      </z-table>
      <z-pagination :small="true" :pagination="userPagination" :total="userTotal" :page.sync="userQuery.page"
        :limit.sync="userQuery.size" @change="getUserList"></z-pagination>
    </el-dialog>
    <!-- 添加用戶 -->
    <!-- <el-dialog title="快速添加用户" :visible.sync="addUserDialogShow" width="50%">
      <el-form label-width="100px">
        <el-form-item label="选择用户">
          <el-select style="width:100%" v-model="addUsers" multiple filterable remote :remote-method="getUserOptions">
            <el-option v-for="u in userOptions" :key="u.userid" :label="`${u.userid} ${u.username}`" :value="u.userid">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogShow = false">取消</el-button>
        <el-button type="primary" @click="submmitAddUser" :loading="submitAddUserLoading">确定</el-button>
      </span>
    </el-dialog> -->
    <!-- <adduser :addUserShow="addUserShow" :currentId='currentId' @cancelAddUser="cancelAddUser">
    </adduser> -->
    <use-select v-if="selectVisible" ref="useselect" @closed="selectVisible=false" @change="useSelectChange">
    </use-select>
  </div>
</template>

<script>
import { generateTree, dateTools } from '@/utils'
import commonMixin from '@/views/_common/mixin'
import _ from 'lodash'
import useSelect from '@/components/Select'
import adduser from '@/views/platform/admin/components/addUser.vue'

export default {
  name: 'adminRole',
  mixins: [commonMixin],
  components: {
    useSelect,
    adduser,
  },
  data: function () {
    return {
      name: '角色',
      api: this.$api.role,
      baseUrl: this.$api.baseUrl,
      saveMenuLoading: false,
      saveEmpLoading: false,
      menuTreeShow: false,
      allChooseflag: true,
      currentId: '',
      treeLoading: false,
      permissionJson: [],
      columns: [
        { title: '角色代码', key: 'role_code' },
        { title: '角色名称', key: 'role_name' },
        { title: '角色描述', key: 'role_desc' },
        { title: '修改人', key: 'modify_user', width: 200 },
        { title: '修改时间', key: 'modify_time', width: 200 },
      ],
      fields: [
        { title: '角色代码', key: 'role_code', required: true },
        { title: '角色名称', key: 'role_name', required: true },
        { title: '角色描述', key: 'role_desc' },
      ],
      tableProps: {
        border: true,
        opsColWith: 180,
        highlightCurrentRow: true,
      },
      formProps: {
        dialogWidth: '70%',
        labelWidth: '140px',
      },
      pagination: {
        // 分页组件配置 如不需分页，可以把pagination设置为null
        layout: 'prev, pager, next, jumper, ->, total, sizes',
      },
      treeData: [],
      menuData: [],
      menuIds: [],
      menuCheckChange: false,
      menuType: { MENU: '目录', WEB: 'Web功能', PDA: 'PDA功能', WIN: 'Client端功能' },
      userColumns: [
        { title: '用户账号', key: 'userid' },
        { title: '用户姓名', key: 'username' },
        { title: '修改人', key: 'modify_user', width: 120 },
        { title: '修改时间', key: 'modify_time', width: 180 },
      ],
      userTableProps: {
        border: true,
        opsColWith: 80,
        highlightCurrentRow: true,
      },
      userQuery: {
        queryString: '',
        size: 10,
        page: 1,
      },
      userPagination: {
        layout: 'prev, pager, next',
      },
      userTableLoading: false,
      userList: [],
      userTotal: 0,
      userOptions: [],
      addUserDialogShow: false,
      addUsers: [],
      submitAddUserLoading: false,
      userRoleDialogShow: false,
      // 管理用户组件
      addUserShow: false,
      selectVisible: false,
      value: [],
    }
  },
  methods: {
    selectHandle(type, data) {
      this.selectVisible = true
      this.$nextTick(() => {
        this.$refs.useselect.open(type, data)
      })
    },
    useSelectChange(data) {
      let users = []
      data.forEach((x) => {
        users.push(x.id)
      })
      let Data = {
        rid: this.currentId,
        users,
      }
      this.$request(this.baseUrl + 'Platform/role/addRoleUsers', Data, 'post')
        .then((r) => {
          this.$message.success('添加成功')
          this.setRoleUser({ id: this.currentId })
        })
        .catch((r) => {
          this.$message.success('添加失败')
        })
    },
    // 管理组件
    cancelAddUser() {
      this.addUserShow = false
    },
    init() {
      this.$request(this.$api.menu + 'getlist', { page: 1, size: 9999 })
        .then((r) => {
          r.forEach((i) => {
            // i.disabled = true
            i.choose_power_codes = []
            i.permissionOptions = this.getMenuPermissJson(i.power_codes ? i.power_codes.split(',') : [], true)
          })
          this.menuData = r
          this.treeData = generateTree(r, 'id', 'parent_id', '0')
        })
        .catch(() => {})
    },
    // 查询当前菜单页面权限选项
    getMenuPermissJson(arr, flag) {
      if (!arr.length) return []
      let arrOptions = []
      arr.forEach((i) => {
        this.permissionJson.find((j) => {
          if (i == j.value) {
            arrOptions.push(j)
          }
        })
      })
      if (flag) {
        return arrOptions
      } else {
        return arrOptions.map((i) => i.value)
      }
    },
    setMenuTree(row) {
      this.currentId = row.id
      this.getRoleMenu()
      this.menuTreeShow = true
      this.allChooseflag = true // 默认需要全选
    },
    checkChange(data, flag) {
      this.menuCheckChange = true
      if (!flag) {
        data.choose_power_codes = []
      } else {
        let tmp = this.menuData.find((x) => x.id == data.id)
        if (!data.choose_power_codes.length) data.choose_power_codes = tmp.power_codes ? tmp.power_codes.split(',') : []
      }
    },
    allChoose() {
      let data = _.cloneDeep(this.menuData)
      this.menuIds = []
      if (this.allChooseflag) {
        this.menuIds = data.map((i) => i.id)
        data.forEach((i) => {
          i.choose_power_codes = this.getMenuPermissJson(i.power_codes ? i.power_codes.split(',') : [])
        })
      }
      this.treeData = generateTree(data, 'id', 'parent_id', '0')
      this.allChooseflag = !this.allChooseflag
      this.menuCheckChange = true
    },
    getRoleMenu() {
      this.menuCheckChange = false
      this.menuIds = []
      this.refreshTree()
    },
    changeCheckbox(data, value) {
      this.menuCheckChange = true
      if (value == 'query') {
        if (data.choose_power_codes.includes('query')) {
          this.$refs.tree.setChecked(data.id, true)
        } else {
          this.$refs.tree.setChecked(data.id, false)
        }
      } else {
        data.choose_power_codes = [...data.choose_power_codes, 'query']
        this.$refs.tree.setChecked(data.id, true)
      }
    },
    saveRoleMenu() {
      this.saveMenuLoading = true
      var nodes = this.$refs.tree.getCheckedNodes(false, true)
      let nodesClone = _.cloneDeep(nodes)
      var arr = nodesClone.map((i) => {
        return {
          menu_id: i.id,
          power_codes: i.choose_power_codes.length ? i.choose_power_codes : [],
        }
      })
      this.$request(this.api + 'setMenus', { role_id: this.currentId, menu_powers: arr }, 'post')
        .then((r) => {
          this.submitLoading = false
          this.$message({
            message: '操作成功',
            type: 'success',
          })
          this.saveMenuLoading = false
          this.menuCheckChange = false
          this.menuTreeShow = false
          this.refreshTree()
        })
        .catch(() => {
          this.saveMenuLoading = false
        })
    },
    refreshTree() {
      this.treeData = []
      if (this.currentId) {
        this.treeLoading = true
        this.$request(this.api + 'getmenubyroleid', { id: this.currentId })
          .then((r) => {
            let data = _.cloneDeep(this.menuData)
            let menuArr = []
            r.map((i) => {
              menuArr.push(r.menu_id)
              let arr = data.find((j) => j.id == i.menu_id && j.resource_type !== 'MENU')
              if (!!arr) {
                this.menuIds.push(arr.id)
                arr.choose_power_codes = i.power_codes || []
                arr.id = i.menu_id
              }
            })
            if (menuArr.length == data.length) {
              for (let x = 0; x < data.length; x++) {
                if (data[x].choose_power_codes == r[x].power_codes) {
                  this.allChooseflag = false
                }
              }
            }
            this.treeData = generateTree(data, 'id', 'parent_id', '0')
            this.treeLoading = false
          })
          .catch(() => {
            this.treeLoading = false
          })
      }
    },
    setRoleUser(row) {
      this.currentId = row ? row.id : 0
      this.userRoleDialogShow = true //原来
      // this.addUserShow = true
      this.researchUser()
    },
    // 搜索用户
    researchUser() {
      this.userQuery.page = 1
      this.getUserList()
    },
    getUserList() {
      this.userTableLoading = true
      this.$request(this.api + 'getempbyroleid', {
        ...this.userQuery,
        id: this.currentId,
      })
        .then((r) => {
          this.userTableLoading = false
          this.userList = r.list
          this.userTotal = r.total
        })
        .catch(() => {
          this.userTableLoading = false
        })
    },
    addUserClick() {
      this.addUserShow = true
      this.value = []
      this.selectHandle(1, this.value)
      // this.addUserDialogShow = true
    },
    getUserOptions(v) {
      this.$request(this.$api.user + 'getlist', { page: 1, size: 200, queryString: v }).then((r) => {
        this.userOptions = r.list
      })
    },
    // 给角色添加绑定的用户
    submmitAddUser() {
      if (!this.addUsers || this.addUsers.length == 0) return this.$message.error('没有需要添加的用户')
      this.submitAddUserLoading = true
      this.$request(
        this.api + 'addRoleUsers',
        {
          rid: this.currentId,
          users: this.addUsers,
        },
        'post',
      )
        .then((r) => {
          this.$message.success('操作成功')
          this.addUserDialogShow = false
          this.submitAddUserLoading = false
          this.addUsers = []
          this.getUserList()
        })
        .catch(() => {
          this.submitAddUserLoading = false
        })
    },
    //User的删除
    deleteUserRoleItem(row) {
      this.$confirm('确定要删除这条记录？')
        .then((r) => {
          this.$request(this.api + 'deleteRoleUser/' + row.id, {}, 'post')
            .then((r) => {
              this.$message.success('操作成功')
              this.getUserList()
            })
            .catch(() => {})
        })
        .catch((e) => {})
    },
  },
  created: function () {
    this.getList()
    this.init()
    this.$request(this.$api.dictionary + 'getdirectchildren', {
      parentType: 'page_permission',
    }).then((r) => {
      this.permissionJson = r
    })
  },
  watch: {
    data: function (val) {},
    // value: {
    //   immediate: true,
    //   deep: true,
    //   handler() {
    //     console.log(this.value)
    //   },
    // },
  },
}
</script>

<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 12px;
  padding-right: 8px;
}
.treeWrap ::v-deep .el-dialog__body {
  margin-top: -28px;
}
::v-deep .el-checkbox__label {
  font-size: 12px !important;
}
</style>
